<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\BuilderPlus\components\Button;
use addons\BuilderPlus\components\Column;
use addons\BuilderPlus\components\Edit;
use addons\BuilderPlus\components\Search;
use addons\BuilderPlus\facade\Table;
use app\common\model\Level;
use app\common\tool\Result;
use think\facade\View;
use think\Response;
use app\common\model\Assets;
use app\common\model\Logs;

class User extends Base
{
    public function getOptions(): array
    {
        return [
            'pk' => 'id',
            'model' => \app\common\model\User::class,
            'validate' => \app\admin\validate\User::class,
            'with' => ['assets', 'level'],
            'append' => ['parent_info', 'node_info', 'position_name', 'active_type_name'],
            'fast' => [
                'edit' => 'user/edit',
                'save' => '_save',
                'reset' => 'resetPassword'
            ]
        ];
    }

    public function index($is_active = 1): string
    {
        $table = Table::init($this)
            ->addColumns([
                ['id', 'ID', fn(Column $col) => $col->width(80)],
                ['photo', '头像', fn(Column $col) => $col->lazyImage()->width(100)],
                ['code', '会员编号', fn(Column $col) => $col->width(100)],
                ['nickname', '会员昵称', fn(Column $col) => $col->width(100), fn(Edit $e) => $e->require()],
                ['mobile', '手机号', fn(Column $col) => $col->width(100), fn(Edit $e) => $e->number()->require()],
                ['parent_code', '推荐人编号', fn(Column $col) => $col->hide(), fn(Edit $e) => $e->type(1)->require()],
                ['parent_info', '推荐人'],
                ['node_code', '安置人编号', fn(Column $col) => $col->hide(), fn(Edit $e) => $e->type(1)->require()],
                ['node_info', '安置人'],
                ['position', '安置位置', fn(Column $col) => $col->hide(),
                    fn(Edit $e) => $e->type(1)->radio(getNodePosition())->require()],
                ['position_name', '安置位置'],
                ['password', '登录密码', fn(Column $col) => $col->hide(), fn(Edit $e) => $e->password()],
                ['pay_password', '支付密码', fn(Column $col) => $col->hide(), fn(Edit $e) => $e->password()],
                ['level_id', '会员等级', fn(Column $col) => $col->templet('{{d.level?d.level.title:"无"}}')]
            ]);
        foreach (Assets::getFields(3) as $field => $title) {
            $table->addColumn($field, $title, fn(Column $col) => $col->withSort('assets')
                ->templet('{{d.assets.' . $field . '}}'));
        }
        return $table
            ->addColumns([
                ['push_num', '直推正式会员个数'],
                ['team_num', '团队正式会员个数'],
                ['my_total', '个人业绩'],
                ['team_total', '团队业绩'],
                ['num_1', '左区人数'],
                ['num_2', '右区人数'],
                ['total_1', '左区业绩'],
                ['total_2', '右区业绩'],
                ['surplus_1', '左区结余'],
                ['surplus_2', '右区结余'],
                ['total_income', '累计收益'],
                $is_active == 2 ? ['active_type_name', '激活方式'] : [],
                $is_active == 2 ? ['active_time', '激活时间', fn(Column $col) => $col->width(150)] : [],
                ['create_time', '注册时间', fn(Column $col) => $col->width(150)],
                ['is_lock', '锁定', fn(Column $col) => $col->switch('锁定|正常', '1|0')->fixed('right')]
            ])
            ->addTopButtons([
                'add',
                'password' => fn(Button $btn) => $btn->title('重置登录密码')
                    ->icon('layui-icon-leaf')
                    ->class('danger')
                    ->url(url('reset')->build())
                    ->placeholder('默认密码111111')
                    ->event('prompt'),
                'pay_password' => fn(Button $btn) => $btn->title('重置支付密码')
                    ->icon('layui-icon-leaf')
                    ->class('danger')
                    ->url(url('reset')->build())
                    ->placeholder('默认密码222222')
                    ->event('prompt')
            ])
            ->addRightButtons([
                'login' => fn(Button $btn) => $btn->title('登录')
                    ->url(url('login')->build())
                    ->customEvent('login'),
                'edit',
                'active' => fn(Button $btn) => $btn->title('激活')
                    ->class('warm')
                    ->url(url('active')->build())
                    ->scriptlet('{{# if (d.is_active == 1) { }}', '{{# } }}')
                    ->event('submit'),
                'delete' => fn(Button $btn) => $btn->scriptlet('{{# if (d.is_active == 1) { }}', '{{# } }}')
            ], $is_active == 1 ? 240 : 150)
            ->addSearch([
                ['create_time', '注册时间', fn(Search $search) => $search->type('date')],
                $is_active == 2 ? ['active_time', '激活时间', fn(Search $search) => $search->type('date')] : [],
                ['code__nickname__mobile', '会员编号/昵称/手机号', fn(Search $search) => $search->condition('Like')],
                ['parent_id', '推荐人编号/昵称/手机号', fn(Search $search) => $search
                    ->relation('\app\common\model\User', 'code|nickname|mobile,id')
                    ->condition('Like')],
                ['node_id', '安置人编号/昵称/手机号', fn(Search $search) => $search
                    ->relation('\app\common\model\User', 'code|nickname|mobile,id')
                    ->condition('Like')]
            ])
            ->addSearchTab([
                ['level_id', '会员等级', fn(Search $search) => $search->type('radio')
                    ->optionValue(Level::column('title', 'id'))]
            ])
            ->setSortType(['active_time' => 'desc', 'id' => 'desc'])
            ->specifyQuery([['is_active', '=', $is_active]])
            ->enableExport()
            ->fetch();
    }

    public function choose(): string
    {
        $table = Table::init($this)
            ->setCheckbox(false)
            ->addColumns([
                ['id', 'ID', fn(Column $col) => $col->width(80)],
                ['photo', '头像', fn(Column $col) => $col->lazyImage()->width(100)],
                ['code', '会员编号', fn(Column $col) => $col->width(100)],
                ['nickname', '会员昵称', fn(Column $col) => $col->width(100)],
                ['mobile', '手机号', fn(Column $col) => $col->width(100)]
            ]);
        foreach (Assets::getFields(3) as $field => $title) {
            $table->addColumn($field, $title, fn(Column $col) => $col->withSort('assets')
                ->templet('{{d.assets.' . $field . '}}'));
        }
        return $table
            ->addColumns([
                ['create_time', '注册时间', fn(Column $col) => $col->minWidth(150)],
                ['btn', '操作', fn(Column $col) => $col->width(100)
                    ->templet('<a class="layui-btn layui-btn-sm">选择</a>')->fixed('right')]
            ])
            ->addSearch([
                ['create_time', '注册时间', fn(Search $search) => $search->type('date')],
                ['code__nickname__mobile', '会员编号/昵称/手机号', fn(Search $search) => $search->condition('Like')]
            ])
            ->fetch();
    }

    public function delete(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn($this->model::_delete($param, $this->admin));
    }

    public function login(): Response
    {
        try {
            $id = $this->request->post('id');
            $user = $this->model::where(['id' => $id])->find();
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            $url = $this->system['uni_path'] . '?token=' . $token;
            $msg = '登录操作，会员【' . $user->id . '】【' . $user->code . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);

            return Result::success('登录成功', ['code' => $user->code, 'url' => $url]);
        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }
    }

    public function active(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn($this->model::emptyActive($param, $this->admin));
    }

    public function checkBalance(): Response
    {
        $param = $this->request->get();
        $account = $param['account'];
        $assets = Assets::where(['uid' => $param['uid']])->field("uid,{$account}")->find();
        if (!isset($assets[$account])) {
            return Result::fail('查询失败');
        }

        return Result::success('success', $assets->$account);
    }

    public function recharge(): Response|string
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            try {
                validate(\app\admin\validate\Recharge::class)->check($param);
            } catch (\Exception $e) {
                return Result::fail($e->getError());
            }

            return Result::fastReturn($this->model::recharge($param, $this->admin));
        }
        View::assign('assets', Assets::getFields(3));

        return View::fetch();
    }
}